package com.cat.DataStructure04;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/sum-of-prefix-scores-of-strings/
 * @create 2025/11/26 15:06
 * @since JDK17
 */

public class Solution15 {
    static int N = ((int) 1e5), cnt;
    static int[][] tree = new int[N][26];
    static int[] pass = new int[N];
    static void clear() {
        for (int i = 1; i <= cnt; i++) {
            Arrays.fill(tree[i], 0);
            pass[i] = 0;
        }
    }
    static void insert(String word) {
        int cur = 1;
        for (int i = 0, path; i < word.length(); i++) {
            path = word.charAt(i) - 'a';
            if (tree[cur][path] == 0) {
                tree[cur][path] = ++cnt;
            }
            pass[cur]++;
            cur = tree[cur][path];
        }
    }
    static int search(String word) {
        int cur = 1, ans = 0;
        for (int i = 0, path; i < word.length(); i++) {
            path = word.charAt(i) - 'a';
            ans += pass[cur];
            cur = tree[cur][path];
        }

        return ans;
    }
    public int[] sumPrefixScores(String[] words) {
        int n = words.length;
        int[] ans = new int[n];
        cnt = 1;
        for (var x : words) {
            insert(x);
        }
        for (int i = 0; i < n; i++) {
            ans[i] = search(words[i]);
        }
        return ans;
    }
}
